<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { deleteTableDataApi, getTableDataApi, saveSortDataApi, saveTableDataApi } from "@/api/course/chapter"
import { UploadUrl } from "@/api/common/common"
import { type TableData, type CreateOrUpdateTableRequestData, type SortData } from "@/api/course/types/chapter"
import {
  type FormInstance,
  type FormRules,
  ElMessage,
  ElMessageBox,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus"
import { CirclePlus, RefreshRight, Sort } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "courseChapter"
})

const loading = ref<boolean>(false)
const courseId = ref<number>(0)
const courseTitle = ref<string>("")

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: 0,
  title: "",
  course_id: 0,
  intro: "",
  sort_num: 0,
  is_use: 10
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  title: [{ required: true, trigger: "blur", message: "章节标题不能为空" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除分类：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion
//#region 改
const handleUpdate = (row: TableData) => {
  dialogVisible.value = true
  console.log(row)
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref<TableData[]>([])
const getTableData = () => {
  loading.value = true
  getTableDataApi({ id: courseId.value })
    .then((data) => {
      tableData.value = data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
//#endregion
import { useRoute } from "vue-router"
import { CreateOrUpdateLessonRequestData } from "@/api/course/types/lesson"
import { getToken } from "@/utils/cache/cookies"
import { deleteLessonDataApi, getLessonInfoApi, saveLessonDataApi } from "@/api/course/lesson"
const route = useRoute()
onMounted(() => {
  formData.value.course_id = Number(route.query.cid)
  courseId.value = Number(route.query.cid)
  courseTitle.value = route.query.title as string
  getTableData()
})

const DEFAULT_LESSON_DATA: CreateOrUpdateLessonRequestData = {
  id: 0,
  title: "",
  course_id: 0,
  chapter_id: 0,
  is_use: 10,
  sort_num: 0,
  intro: "",
  video_url: ""
}

//#region 视频内容添加
const lessonRef = ref<FormInstance | null>(null)
const lessonVisible = ref<boolean>(false)
const lessonFormData = ref<CreateOrUpdateLessonRequestData>(cloneDeep(DEFAULT_LESSON_DATA))
const lessonRules: FormRules<CreateOrUpdateLessonRequestData> = {
  title: [{ required: true, trigger: "blur", message: "请输入视频内容标题" }],
  course_id: [{ required: true, trigger: "blur", message: "课程不能为空" }],
  video_url: [{ required: true, trigger: "blur", message: "视频不能为空" }]
}
const videoUpload = ref<UploadInstance>()
const token = getToken()
const headers = { authorization: token }

const handleVideoSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res)
  lessonFormData.value.video_url = res.body.url
}

const beforeVideoUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type !== "video/mp4") {
    ElMessage.error("上传的视频必须是MP4格式!")
    return false
  } else if (rawFile.size > 1 * 1024 * 1024 * 1024) {
    ElMessage.error("上传的视频不能超过1GB!")
    return false
  }
  return true
}

const handleExceed: UploadProps["onExceed"] = (files) => {
  videoUpload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  videoUpload.value!.handleStart(file)
}
const handleLesson = (row: TableData) => {
  lessonFormData.value.course_id = row.course_id
  lessonFormData.value.chapter_id = row.id
  lessonVisible.value = true
}

const lessonCreateOrUpdate = () => {
  lessonRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    console.log(lessonFormData.value)
    saveLessonDataApi(lessonFormData.value)
      .then(() => {
        ElMessage.success("操作成功")
        lessonVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const handleLessonUpdate = (row: TableData) => {
  getLessonInfoApi({ id: row.id }).then((data) => {
    lessonFormData.value = cloneDeep(data)
    lessonVisible.value = true
  })
}
const resetLessonForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const handleLessonDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除课程内容：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteLessonDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

const UpdateSortData = () => {
  const sortDatas = [] as SortData[]
  for (let i = 0; i < tableData.value.length; i++) {
    const item = tableData.value[i]
    sortDatas.push({
      id: item.id,
      sort_num: Number(item.sort_num),
      type: item.type
    })
    if (Array.isArray(item.children) && item.children.length > 0) {
      for (let j = 0; j < item.children.length; j++) {
        const child = item.children[j]
        sortDatas.push({
          id: child.id,
          sort_num: Number(child.sort_num),
          type: child.type
        })
      }
    }
  }

  saveSortDataApi({ data: sortDatas }).then(() => {
    ElMessage.success("操作成功")
    getTableData()
  })
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div style="width: 100%">
        <h2>{{ courseTitle }}</h2>
        <el-divider />
      </div>
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增章节</el-button>
          <el-button type="default" :icon="Sort" @click="UpdateSortData()">更新排序</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" row-key="row_id" default-expand-all>
          <el-table-column prop="title" label="章节名称" align="left" />
          <el-table-column prop="sort_num" label="排序号" align="center" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.sort_num" type="number" />
            </template>
          </el-table-column>
          <el-table-column prop="is_use" label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.is_use == 10" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="280" align="right">
            <template #default="scope">
              <div v-if="scope.row.type == 'chapter'">
                <el-button type="warning" bg size="small" @click="handleLesson(scope.row)"> 添加视频 </el-button>
                <el-button type="primary" bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="danger" bg size="small" @click="handleDelete(scope.row)">删除</el-button>
              </div>
              <div v-else>
                <el-button type="primary" bg size="small" @click="handleLessonUpdate(scope.row)">修改</el-button>
                <el-button type="danger" bg size="small" @click="handleLessonDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === 0 ? '新增章节' : '修改章节'"
      @closed="resetForm"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="top">
        <el-form-item prop="title" label="章节名称" required>
          <el-input v-model="formData.title" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item prop="intro" label="章节介绍">
          <el-input type="textarea" v-model="formData.intro" :rows="4" placeholder="请输入章节介绍" />
        </el-form-item>
        <el-form-item prop="sort_num" label="排序号">
          <el-input v-model="formData.sort_num" type="number" placeholder="排序号" />
        </el-form-item>
        <el-form-item prop="is_use" label="状态" required>
          <el-select v-model="formData.is_use" placeholder="选择状态">
            <el-option label="启用" :value="10" />
            <el-option label="禁用" :value="20" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 视频内容谈层 -->
    <el-dialog v-model="lessonVisible" title="修改视频内容" @closed="resetLessonForm" width="50%">
      <el-form ref="lessonRef" :model="lessonFormData" :rules="lessonRules" label-width="100px" label-position="top">
        <el-form-item prop="title" label="内容名称" required>
          <el-input v-model="lessonFormData.title" placeholder="请输入内容名称" />
        </el-form-item>
        <el-form-item prop="intro" label="内容介绍">
          <el-input type="textarea" v-model="lessonFormData.intro" :rows="3" placeholder="请输入内容介绍" />
        </el-form-item>
        <el-form-item prop="video_url" label="内容视频" required>
          <el-upload
            ref="videoUpload"
            :action="UploadUrl"
            :limit="1"
            :headers="headers"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
            :on-exceed="handleExceed"
            :show-file-list="false"
            style="width: 100%"
          >
            <el-button type="primary" style="margin-bottom: 10px"> 上传视频 </el-button>
          </el-upload>
          <el-input v-model="lessonFormData.video_url" placeholder="请输入视频链接或上传视频" />
        </el-form-item>
        <el-form-item prop="is_use" label="状态" required>
          <el-select v-model="lessonFormData.is_use" placeholder="选择状态">
            <el-option label="启用" :value="10" />
            <el-option label="禁用" :value="20" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="lessonVisible = false">取消</el-button>
        <el-button type="primary" @click="lessonCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
